package cn.hhchat.wp.entity;

import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;

import cn.hhchat.wp.dto.post.DetailPost;
import cn.hhchat.wp.dto.post.SimplePost;
import cn.hhchat.wp.util.DateUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.*;
import org.hibernate.annotations.CascadeType;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created this one by HMH on 2017/10/22.
 */
@Getter
@Setter
@AllArgsConstructor
@Entity
@Table(name = "post_entity")
public class PostEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(columnDefinition = "LONGTEXT")
    private String content;

    @Column(columnDefinition = "LONGTEXT")
    private String markContent;

    private int weekOfYear;

    private int year;

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    private GroupEntity group;

    @CreationTimestamp
    private Date createTime;

    @UpdateTimestamp
    private Date updateTime;

    @OneToMany(mappedBy = "post")
    @Cascade(CascadeType.SAVE_UPDATE)
    List<CommentEntity> comments;

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    private UserEntity poster;

    @OneToMany
    @Cascade(CascadeType.SAVE_UPDATE)
    private List<AttachmentEntity> attachments;

    public PostEntity() {
        attachments = new ArrayList<>();
        comments = new ArrayList<>();
    }

    @JsonIgnore
    public SimplePost toSimplePost() {
        SimplePost simplePost = new SimplePost();
        simplePost.setId(this.id);
        simplePost.setUserId(this.poster.getId());
        simplePost.setWeek(this.weekOfYear);
        simplePost.setYear(this.year);
        simplePost.setCommentCount(this.comments.size());
        simplePost.setAttachmentCount(this.attachments.size());
        return simplePost;
    }

    @JsonIgnore
    public DetailPost toDetailPost(String urlRoot) {
        DetailPost detailPost = new DetailPost();
        detailPost.setId(this.id);
        detailPost.setUserId(this.poster.getId());
        detailPost.setWeek(this.weekOfYear);
        detailPost.setYear(this.year);
        detailPost.setCreateTime(DateUtil.formatDateTime(this.createTime));
        detailPost.setUpdateTime(DateUtil.formatDateTime(this.updateTime));
        detailPost.setContent(this.content);
        detailPost.setMarkContent(this.markContent);
        detailPost.setCommentCount(this.comments.size());
        detailPost.setAttachmentCount(this.attachments.size());
        detailPost.setAttachments(this.attachments.stream().map(a->a.toSimpleAttachment(urlRoot)).collect(Collectors.toList()));
        detailPost.setComments(this.comments.stream().map(CommentEntity::toSimpleComment).collect(Collectors.toList()));
        return detailPost;
    }
}

